﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Is.Net {
	/**
	 * Validation utilities for phone numbers.
	 * 
	 * @author Logi Helgu
	 * @converted to C# Ingi Gauti Ragnarsson
	 */

	public class PhoneNumber {

		/**
		 * No instances created, ever.
		 */
		private PhoneNumber() { }

		/**
		 * Checks to see if the given string consists of 7 digits.
		 * 
		 * @returns true if the number is valid.
		 */
		public static bool IsValidatePhoneNumber(String phoneNumber) {

			phoneNumber = CleanPhoneNumber(phoneNumber);

			if (string.IsNullOrEmpty(phoneNumber))
				return false;

			if (phoneNumber.Length != 7)
				return false;

			if (!Regex.IsMatch(phoneNumber, "[0-9]{7}"))
				return false;

			return true;
		}

		/**
		 * Checks to see if the given number is a valid mobile number.
		 * 
		 * According to http://pta.is/displayer.asp?cat_id=23 all mobile numbers start with 6, 7 or 8
		 *
		 * @returns true if the number is valid.
		 */
		public static bool IsValidateMobileNumber(String phoneNumber) {

			if (!IsValidatePhoneNumber(phoneNumber))
				return false;

			String firstLetterInPhoneNumber = phoneNumber.Substring(0, 1);

			return "6" == firstLetterInPhoneNumber || "7" == firstLetterInPhoneNumber || "8" == firstLetterInPhoneNumber;
		}

		/**
		 * Cleans up phone number by trimming, removing white spaces and - sign
		 * */
		public static String CleanPhoneNumber(String phoneNumber) {
			if (!string.IsNullOrEmpty(phoneNumber)) {
				phoneNumber = phoneNumber.Trim();
				phoneNumber = phoneNumber.Replace("+354", "");
				phoneNumber = phoneNumber.Replace(" ", "");
				phoneNumber = phoneNumber.Replace("-", "");
			}
			return phoneNumber;
		}
	}

}
